<?php

include('sqlconnect.php');

if ($_POST) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $rpass = $_POST['rpass'];
    $email = $_POST['email'];
    $input_error = false;



    // Email
    if (preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
        $valid_email = $email;
    } else {
        $error_email = 'Enter valid Email.';
    }

    if (preg_match('/^[A-Za-z0-9_]{3,20}$/', $username)) {
        $valid_username = $username;
    } else {
        $error_username = 'Username is required';
    }

// Password min 6 char max 20 char
    if (preg_match('/^[A-Za-z0-9!@#$%^&*()_]{6,20}$/', $password)) {
        $valid_password = $password;
        $valid_password = md5($password);
    } else {
        $error_password = 'Enter valid Password. Min. 6 Characters.';
    }
	
	$sql = "SELECT * FROM users WHERE username = $username";
	$result = mysql_query($sql);
	$num_rows = mysql_num_rows($result);
	if ($num_rows > 0) {
		$error_username = "Username already taken";
	} 

    if ((strlen($valid_email) > 0) && (strlen($valid_username) > 0) && (strlen($valid_password) > 0 && $num_rows==0)) {
        if (!mysql_query("INSERT INTO users (username, password, email,type) VALUES ('$_POST[username]','$valid_password','$_POST[email]','2')")) 
		{
            die('Error: ' . mysql_error());
            echo '1';
        }

        else
            echo '0';
    }
}
?>